import string
import time
import random

import redis
from captcha.image import ImageCaptcha
from django.http import HttpResponse
from django.shortcuts import render
from jwt import ExpiredSignatureError, DecodeError
from rest_framework.response import Response
from rest_framework.views import APIView
import jwt

from oaxitong import settings
from users.models import Users, JueSe, CaiJue, CaiDan


# 登陆接口在没有账号的时候注册
class Register(APIView):

    def post(self, request):

        account = request.data.get('account')   # 账号
        password = request.data.get('password')     # 密码
        img = request.data.get('img')   # 图片验证码
        uuid = request.data.get('uuid')     # 用户uuid

        # 判断信息是否完整
        if not all([account, password, img, uuid]):
            return Register({'code': 500, 'msg': '信息不完整'})

        # 判断图形验证码
        red = redis.Redis()
        image = red.get('user:%s') % uuid
        if img == image.decode('utf-8'):
            user = Users.objects.filter(username=account).first()
            if not user:
                Users.objects.create(username=account,password=password)
                token = self.gen_token(account)
                return Response({"code": 200, "msg": "新用户第一次注册，需1000手续费", 'img_url': '', 'token': token})

            else:
                if user.password == password:

                    token = self.gen_token(account)
                    return Response({"code": 200,"msg": "登陆成功", 'token': token})
                else:
                    return Response({"code": 204, "msg": "密码不正确"})

        else:
            return Register({'code': 500, 'msg': '图形验证码不正确'})

    @staticmethod
    def gen_token(name):

        payload = {
            'username': name,
            'exp': time.time() + 60000
        }

        token = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm='HS256')
        return token


# 校验token
def check_token(token):
    try:
        payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms=['HS256'])
        print('payload>>>>>', payload)
        return payload
    except ExpiredSignatureError:
        print("token过期")
        return Response({"code": 409, "msg": "token过期"})
    except DecodeError:
        return Response({"code": 408, "msg": "请重新登录"})


# 图片验证码
class UsersCode(APIView):
    def get(self, request, uuid):
        alpha_number = string.ascii_letters + string.digits
        img_code = ''.join(random.sample(alpha_number, 4))
        img_capt = ImageCaptcha()
        img_code_captcha = img_capt.generate(img_code)
        redis_conn = redis.Redis(host='localhost', port=6379, db=0)
        key = 'image_code:%s'%uuid
        redis_conn.set(key, img_code, ex=300)
        redis_conn.close()
        return HttpResponse(img_code_captcha, content_type='image/png')


# 校验图片验证码
class CheckImageCode(APIView):
    def get(self, request):
        uuid_ = request.query_params.get('imageCodeID')
        image_code = request.query_params.get('imageCode')
        key = 'image_code:%s'%uuid_
        redis_conn = redis.Redis(host='localhost', port=6379, db=0)
        stored_image_code = redis_conn.get(key)
        if not stored_image_code:
            return Response({'code': 204, 'msg': '图片验证码已过期'})
        if stored_image_code.decode().lower() == image_code.lower():
            return Response({'code': 200, 'msg': '图片验证码成功'})
        return Response({'code': 204, 'msg': '图片验证码失败'})


# 找回密码
class RetrieveViews(APIView):
    def post(self, request):
        token = request.headers.get('Authorization')
        user = check_token(token)

        password = request.data.get('password')     # 密码
        pwd = request.data.get('pwd')   # 确认密码

        if not user:
            return Response({'code': 401, 'msg': '未登陆'})

        if not all([password, pwd]):
            return Response({'code': 400, 'msg': '信息不完整'})

        if password == pwd:
            Users.objects.filter(account=user.get('name')).update(password=password)

            return  Response({'code': 200, 'msg': '密码找回成功，请不要再忘了呦，下次再忘记就需要交50元才能找回呦'})
        else:
            return Response({'code': 204, 'msg': '两次密码不一样'})


# 角色管理
class Role(APIView):

    # 添加角色
    def post(self, request):
        roname = request.data.get('roname')     # 获取角色的名字
        menu = request.data.get('menu')     # 获取角色管理的菜单
        remark = request.data.get('remark')     # 当前角色的备注

        juese = JueSe.objects.filter(roname=roname)

        if juese:
            return Response({'code': 400, 'msg': '你添加的角色已存在'})

        JueSe.objects.create(name=roname)
        for i in menu:
            caidan = CaiDan.objects.filter(id=i)
            CaiJue.objects.create(juese=juese, caidan=caidan)
        return Response({'code': 200, 'msg': '添加菜单成功'})








